import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from '@/components/ui/card';
import { Copy, RefreshCw, Globe, Plus, Minus, ChevronDown, ChevronUp } from 'lucide-react';
import OpenAIClient from '@/lib/llm';
import ReactMarkdown from 'react-markdown';
import rehypeHighlight from 'rehype-highlight';
import 'highlight.js/styles/atom-one-dark.css';

const PythonCrawlerGenerator = () => {
  const [url, setUrl] = useState('');
  const [method, setMethod] = useState('GET');
  const [headers, setHeaders] = useState([{ key: '', value: '' }]);
  const [body, setBody] = useState('');
  const [selectors, setSelectors] = useState('');
  const [output, setOutput] = useState('');
  const [responseType, setResponseType] = useState('html'); // 默认响应类型为HTML
  const [jsonPaths, setJsonPaths] = useState([{ path: '', alias: '' }]); // JSON路径提取配置
  const [showJsonHelp, setShowJsonHelp] = useState(false); // 显示JSON路径帮助信息
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const client = new OpenAIClient();

  const addHeader = () => {
    setHeaders([...headers, { key: '', value: '' }]);
  };

  const removeHeader = (index) => {
    if (headers.length > 1) {
      const newHeaders = [...headers];
      newHeaders.splice(index, 1);
      setHeaders(newHeaders);
    }
  };

  const updateHeader = (index, field, value) => {
    const newHeaders = [...headers];
    newHeaders[index][field] = value;
    setHeaders(newHeaders);
  };

  const addJsonPath = () => {
    setJsonPaths([...jsonPaths, { path: '', alias: '' }]);
  };

  const removeJsonPath = (index) => {
    if (jsonPaths.length > 1) {
      const newPaths = [...jsonPaths];
      newPaths.splice(index, 1);
      setJsonPaths(newPaths);
    }
  };

  const updateJsonPath = (index, field, value) => {
    const newPaths = [...jsonPaths];
    newPaths[index][field] = value;
    setJsonPaths(newPaths);
  };

  const generatePython = async () => {
    if (!url.trim()) {
      setError('请输入目标网址');
      return;
    }
    
    setLoading(true);
    setError('');
    try {
      const validHeaders = headers.filter(h => h.key && h.value);
      const headersObj = Object.fromEntries(validHeaders.map(h => [h.key, h.value]));
      
      const messages = [
        {
          role: 'system',
          content: `你是一个专业的Python爬虫代码生成器，根据用户需求生成Python爬虫代码。确保代码功能完整且安全。
          只返回Python代码，不要解释。也不要写出\`\`\`python \`\`\`，建议和意见以注释格式写出。
          使用requests库发送HTTP请求，对于HTML响应使用BeautifulSoup解析，对于JSON响应使用json模块处理。`
        },
        {
          role: 'user',
          content: `请生成一个Python爬虫代码，要求：
          目标网址: ${url}
          请求方法: ${method}
          ${validHeaders.length > 0 ? `请求头: ${JSON.stringify(headersObj)}` : ''}
          ${body && method !== 'GET' ? `请求体: ${body}` : ''}
          响应类型: ${responseType}
          ${responseType === 'html' && selectors.trim() ? `CSS选择器: ${selectors.split('\n').filter(s => s.trim()).join(', ')}` : ''}
          ${responseType === 'json' && jsonPaths.some(p => p.path.trim()) ? `JSON路径提取: ${jsonPaths.filter(p => p.path.trim()).map(p => `${p.path}${p.alias.trim() ? ` (别名: ${p.alias})` : ''}`).join(', ')}` : ''}`
        }
      ];
      
      const response = await client.chat(messages);
      setOutput(response);
    } catch (err) {
      console.error('生成Python代码出错:', err);
      setError('生成Python代码时出错，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = () => {
    navigator.clipboard.writeText(output);
  };

  return (
    <Card className="h-full flex flex-col">
      <CardHeader className="pb-3">
        <div className="flex items-center gap-3">
          <Globe className="text-green-500" size={24} />
          <CardTitle>Python爬虫生成器</CardTitle>
        </div>
      </CardHeader>
      <CardContent className="flex-1 grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 左侧输入区域 */}
        <div className="space-y-4">
          <div>
            <label className="block mb-2 text-sm font-medium">目标网址</label>
            <Input
              value={url}
              onChange={(e) => setUrl(e.target.value)}
              placeholder="https://example.com"
            />
          </div>
          
          <div>
            <label className="block mb-2 text-sm font-medium">请求方法</label>
            <div className="grid grid-cols-4 gap-2">
              {['GET', 'POST', 'PUT', 'DELETE'].map((m) => (
                <Button
                  key={m}
                  variant={method === m ? 'default' : 'outline'}
                  onClick={() => setMethod(m)}
                  className="text-xs"
                >
                  {m}
                </Button>
              ))}
            </div>
          </div>
          
          <div>
            <label className="block mb-2 text-sm font-medium">响应类型</label>
            <div className="grid grid-cols-2 gap-2">
              <Button
                variant={responseType === 'html' ? 'default' : 'outline'}
                onClick={() => setResponseType('html')}
                className="text-xs"
              >
                HTML
              </Button>
              <Button
                variant={responseType === 'json' ? 'default' : 'outline'}
                onClick={() => setResponseType('json')}
                className="text-xs"
              >
                JSON
              </Button>
            </div>
          </div>
          
          <div>
            <div className="flex justify-between items-center mb-2">
              <label className="block text-sm font-medium">请求头</label>
              <Button 
                size="icon" 
                variant="ghost" 
                className="h-6 w-6"
                onClick={addHeader}
              >
                <Plus size={16} />
              </Button>
            </div>
            <div className="space-y-2">
              {headers.map((header, index) => (
                <div key={index} className="flex gap-2 items-center">
                  <Input
                    value={header.key}
                    onChange={(e) => updateHeader(index, 'key', e.target.value)}
                    placeholder="Header名称"
                    className="flex-1"
                  />
                  <Input
                    value={header.value}
                    onChange={(e) => updateHeader(index, 'value', e.target.value)}
                    placeholder="Header值"
                    className="flex-1"
                  />
                  <Button 
                    size="icon" 
                    variant="ghost" 
                    className="h-6 w-6"
                    onClick={() => removeHeader(index)}
                    disabled={headers.length <= 1}
                  >
                    <Minus size={16} />
                  </Button>
                </div>
              ))}
            </div>
          </div>
          
          {method !== 'GET' && (
            <div>
              <label className="block mb-2 text-sm font-medium">请求体 (JSON格式)</label>
              <Textarea
                value={body}
                onChange={(e) => setBody(e.target.value)}
                placeholder={'{\n  "key": "value"\n}'}
                className="min-h-[100px] font-mono"
              />
            </div>
          )}
          
          {responseType === 'html' ? (
            <div>
              <label className="block mb-2 text-sm font-medium">CSS选择器 (每行一个)</label>
              <Textarea
                value={selectors}
                onChange={(e) => setSelectors(e.target.value)}
                placeholder="例如：.product-title&#10;#price"
                className="min-h-[100px]"
              />
            </div>
          ) : (
            <div>
              <div className="flex justify-between items-center mb-2">
                <label className="block text-sm font-medium">JSON路径提取</label>
                <Button 
                  size="icon" 
                  variant="ghost" 
                  className="h-6 w-6"
                  onClick={addJsonPath}
                >
                  <Plus size={16} />
                </Button>
              </div>
              <div className="space-y-2">
                {jsonPaths.map((path, index) => (
                  <div key={index} className="flex gap-2 items-center">
                    <Input
                      value={path.path}
                      onChange={(e) => updateJsonPath(index, 'path', e.target.value)}
                      placeholder="JSON路径 (如: data.items[0].name)"
                      className="flex-1"
                    />
                    <Input
                      value={path.alias}
                      onChange={(e) => updateJsonPath(index, 'alias', e.target.value)}
                      placeholder="变量别名"
                      className="w-1/3"
                    />
                    <Button 
                      size="icon" 
                      variant="ghost" 
                      className="h-6 w-6"
                      onClick={() => removeJsonPath(index)}
                      disabled={jsonPaths.length <= 1}
                    >
                      <Minus size={16} />
                    </Button>
                  </div>
                ))}
              </div>
              
              <div className="mt-2">
                <div 
                  className="flex items-center text-sm text-blue-600 cursor-pointer"
                  onClick={() => setShowJsonHelp(!showJsonHelp)}
                >
                  <span>JSON路径使用帮助</span>
                  {showJsonHelp ? <ChevronUp size={16} /> : <ChevronDown size={16} />}
                </div>
                
                {showJsonHelp && (
                  <div className="mt-2 bg-gray-50 p-3 rounded-md text-xs text-gray-600">
                    <p className="font-medium mb-1">JSON路径示例：</p>
                    <ul className="list-disc pl-5 space-y-1">
                      <li><code>data.items</code> - 获取items数组</li>
                      <li><code>data.items[0]</code> - 获取items数组的第一个元素</li>
                      <li><code>data.items[0].name</code> - 获取第一个元素的name属性</li>
                      <li><code>user.address.city</code> - 获取嵌套对象的city属性</li>
                    </ul>
                    <p className="mt-2">变量别名用于存储提取的值，如不填写将自动生成</p>
                  </div>
                )}
              </div>
            </div>
          )}
        </div>
        
        {/* 右侧代码区域 */}
        <div className="flex flex-col">
          <label className="block mb-2 text-sm font-medium">生成的Python代码</label>
          <div className="relative">
            <div className="bg-gray-50 rounded-md p-4 font-mono text-sm overflow-auto min-h-[200px]">
              {loading && <div>生成中...</div>}
              {error && <div className="text-red-500">{error}</div>}
              {output ? (
                 <div className="prose prose-zinc max-w-none dark:prose-invert min-h-[100px] w-full">
                   <ReactMarkdown 
                     rehypePlugins={[rehypeHighlight]}
                   >
                     {`\`\`\`python\n${output}\n\`\`\``}
                   </ReactMarkdown>
                 </div>
               ) : (
                 <div className="bg-gray-50 rounded-md p-4 font-mono text-sm text-gray-500 min-h-[100px] w-full">
                   生成的Python代码将显示在这里
                 </div>
               )}
            </div>
            {output && !loading && (
              <Button 
                size="icon" 
                variant="ghost" 
                className="absolute top-2 right-2"
                onClick={copyToClipboard}
              >
                <Copy size={16} />
              </Button>
            )}
          </div>
        </div>
      </CardContent>
      <CardFooter>
        <Button onClick={generatePython} className="w-full" disabled={loading}>
          {loading ? (
            <>加载中...</>
          ) : (
            <> <RefreshCw className="mr-2" size={16} /> 生成爬虫 </>
          )}
        </Button>
      </CardFooter>
    </Card>
  );
};

export default PythonCrawlerGenerator;